from django.http import HttpResponse, request
from django.shortcuts import render, redirect
from django import forms
from ManageApp.models import MyAdmin
import hashlib
from django.conf import settings
# setting文件里有SECRET_KEY


def get_md5(data):
    obj = hashlib.md5(settings.SECRET_KEY.encode("utf-8"))
    obj.update(data.encode("utf-8"))
    return obj.hexdigest()


class LoginForm(forms.Form):
    user_name = forms.CharField(label='用户名', widget=forms.TextInput(attrs={
            "class": "form-control",  # 给输入框添加 Bootstrap 样式类，使它看起来更美观
            "placeholder": "用户名"}))
    password = forms.CharField(label='密码', required=True,
                               widget=forms.PasswordInput(attrs={"class": "form-control", "placeholder": "密码"},
                                                          render_value=True))  # render_value代表刷新不清空

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return get_md5(pwd)


def login(req):
    if req.method == "GET":
        form = LoginForm()
        return render(req, 'login.html', {'form': form})
    form = LoginForm(data=req.POST)
    if form.is_valid():
        user_name = form.cleaned_data.get('user_name')
        password = form.cleaned_data.get('password')
        print(req.session)
        print(req.session.get("info"))
        adm_obj = MyAdmin.objects.filter(user_name=user_name, password=password).first()
        if not adm_obj:
            form.add_error(field="password",error="用户名或密码错误")
            # return redirect('/myadmin/list')
            return render(req, 'login.html', {'form': form})
        req.session["info"] = {"id": adm_obj.id, "name": adm_obj.user_name}
        return redirect('/myadmin/list')
    return render(req, 'login.html', {'form': form})


def logout(req):
    req.session.clear()
    return redirect('/')